package com.nervenets.web.controller.handler.admin.user;

import com.nervenets.utils.StringUtils;
import com.nervenets.web.controller.handler.SessionHandler;
import com.nervenets.web.controller.handler.user.UserModel;
import com.nervenets.web.enumeration.Role;
import com.nervenets.web.enumeration.WealthType;
import com.nervenets.web.hibernate.domain.user.User;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Joe on 2018/1/25.
 */
public class UserInvitedListHandler extends SessionHandler<UserFlowParams> {
    @Override
    public ArrayList<Role> allowRoles() {
        return Role.administrator();
    }

    @Override
    public boolean needLog() {
        return false;
    }

    @Override
    public String handle(UserFlowParams params, HttpServletRequest request) throws Exception {
        String hql = "from User where inviteUserId = ? ";
        List<Object> objects = new ArrayList<>();
        objects.add(params.getTargetUserId());
        if (!StringUtils.isEmpty(params.getKeyword())) {
            hql += "and name like ? ";
            objects.add("%" + params.getKeyword() + "%");
        }
        BigDecimal countOfByHql = userDao.getCountOfByHql(hql, objects);
        hql += "order by id desc ";
        List<User> inviteUsers = userDao.getAllObjectsByHql(hql, objects, params.getStart(), params.getLimit());

        List<UserModel> userModels = new ArrayList<>();
        for (User user : inviteUsers) {
            UserModel userModel = new UserModel(user, 2, globalVariablesService.getGlobalRule().getDefaultAvatar());
            userModel.setMoney(globalService.getUserWealthOfMoney(user.getId(), WealthType.money));
            userModels.add(userModel);
        }
        return successMessage(userModels,
                new KeyValue("start", params.getStart()),
                new KeyValue("total", countOfByHql.intValue()));
    }

    @Override
    public String result() throws Exception {
        return null;
    }
}
